<?
require_once("sqlconn.php");
include_once("miscel.php");

/*
	Function: addifnotpresent
	
	Adds an user, identified by token, token secret and screen name, to the DB.
	
	Parameters:
		
		token: Twitter OAauth token.
		token_secret: Twitter OAuth token secret.
		user: User's screen name.
		
	Returns:
		
		True if database was modified, false if not.
*/
function addifnotpresent($token, $token_secret, $user)
{
	// Escape data.
	$token = mysql_real_escape_string($token);
	$token_secret = mysql_real_escape_string($token_secret);
	$user = mysql_real_escape_string($user);
	
	$query="SELECT * FROM users WHERE token='$token'";
	$result = @mysql_query($query) or logs("Error in query: $query \n\t" . mysql_error());
	$num_results = @mysql_num_rows($result);
	if ($num_results == 0)
	{
		$query="INSERT INTO users (token, token_secret, user) VALUES ('$token', '$token_secret', '$user')";
		@mysql_query($query) or logs(mysql_error()); 
		return true;
	}
	else if ($num_results == 1)
	{
		return false;
	}
	else if ($num_results > 1)
	{
		// Duplicates: delete all.
		$query="DELETE FROM users WHERE token='$token'";
		$count=@mysql_num_rows(mysql_query($query));
		logs("Found $count duplicates in $token, deleted.");
		return false;
	}
}

/* 
	Function: getTokenSecret
	
	Gets the Token Secret of an user, given its token.
	
	Parameters:
	
		token: Twitter OAuth Token.
		
	Returns:
		
		Array with token secret 'token_secret' and user screen name, 'user'.
*/
function getTokenSecret($token)
{
	$token= mysql_real_escape_string($token);
	$query= "SELECT token_secret, user FROM users WHERE token='$token' LIMIT 1";
	$result = @mysql_query($query) or logs(mysql_error());
	if(mysql_num_rows($result) == 0)
	{
		$j;
		return $j;
	}
	$arr = @mysql_fetch_array($result);
	return $arr;
}

/* 
	Function: getOAuthData
	
	Gets the Token and Token Secret of an user, given its username.
	
	Parameters:
	
		user: user name.
		
	Returns:
		
		Array with token secret 'token_secret' and 'token'.
*/
function getOAuthData($user)
{
	$user= mysql_real_escape_string($user);
	$query= "SELECT token, token_secret FROM users WHERE user='$user' LIMIT 1";
	$result = @mysql_query($query) or logs(mysql_error());
	if(@mysql_num_rows($result) == 0)
	{
		$j= array('token' => '-1', 'token_secret' => '-1');
		return $j;
	}
	$arr = @mysql_fetch_array($result);
	return $arr;
}